
const util = require("../../../utils/util");

const {
  // API的状态码
  succeed,
  failed,
} = require("../../../utils/constant")
const {
  queryDevcieModel,
} = requirePlugin("hello-plugin")
  // 杰理模块
var JlModel;
  // 表盘API
var RCSPOpSystemInfo;
var RCSPOpWatchDial;
var callback;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    deviceType:'',
    fileName: '',
    fileInfo: '',
    fileStatus: 0,//0：未读取，1：读取中，2：已读取
    isTransfering: false,
    transferProgressText: '',
    list: [
       
    ] ,
    dials: [],
    index: -1, // 正在下载的表盘文件索引
    lastIndex: -1, // 记录上一个表盘索引
    showModal: false,
    modalTitle: '下载中...',
    progress: 0,
    vary_width: wx.getSystemInfoSync().windowWidth * 0.5,
    dialsNum: 0,
  },  
  watchList:[],
  defaultWatchList:[],
  dialData: Uint8Array.prototype,
  lastModifyTime: 0,
  // 定义系统自带表盘排除的列表
  systemNames: [
    "WATCH900", "JL","SIDEBAR","BGP_W00",,"FONT",
  ],
  // 定义默认表盘排除的列表
  defaultNames: [
    "WATCH0", "WATCH1", "WATCH2", "WATCH3",
  ],

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    require('../../../lib/index',(mod)=>{
      JlModel = mod
      // 导入管理模块
      JlModel.getBtManager().then(({ systemInfo, watchDial }) => {
        console.log("模块导入成功", systemInfo, watchDial);
        RCSPOpSystemInfo = systemInfo;
        RCSPOpWatchDial = watchDial;
      }).catch(error => {
        console.error("模块导入失败:", error);
      });
    
    }, ({ errMsg, mod }) => {
      console.error(`path: ${mod}, ${errMsg}`)
    })

    // 获取设备型号
    queryDevcieModel((state,res)=>{
      if (state == succeed) {
        console.log("设备型号是：",res);
        this.setData({
          deviceType: res
        })
        // 获取用户缓存信息
        const user = wx.getStorageSync("user");
        console.log("用户token",user?.token);
        // 获取表盘
        util.getDialList(res, user?.token, (res)=>{
          console.log("获取设备表盘信息：" + JSON.stringify(res.data));
          const dials = res.data.data;
          this.setData({ list: dials });
          wx.showToast({
            title: res.data.message
          })
          RCSPOpWatchDial?.getWatchResourseFileList().then((res) => {
            console.log("获取表盘列表", res);
            this.reFresh(res)
          })
          // 表盘回调
          callback= { 
            onEvent: (_event) => {
                switch (_event.type) {
                    case 'NONE':
                        break;
                    case 'UseDialChange'://当前表盘变化
                    // 清除选中状态
                    this.clearActive();
                        //当前使用的表盘
                        const watch = _event.UseDialChange?.dial;
                        console.log("切换表盘",watch);
                        if (watch) {
                          this.chooseWatch(watch.path);
                        }
                        break;
                    case 'WatchResourseFileListChange'://手表Flash资源文件列表变化
                        this.clearActive();
                        //资源文件列表
                        const resourseList = _event.WatchResourseFileListChange?.fileList;
                        this.reFresh(resourseList)
                        // for (let index = 0; index < resourseList.length; index++) {
                        //   const item = resourseList[index];
                        //   this.chooseWatch(item.path);
                        // }
                        break;
                    default:
                        break;
                }
            }
          };
          // 注册回调
          RCSPOpWatchDial?.registerEventCallback(callback);
        })

      } 
    })


  },
  // 刷新组件数据
  reFresh(res){
    const dials = this.data.list;
    for (let index = 0; index < res.length; index++) {
      const element = res[index];
      //@ts-ignore
      element.name = element.getName();
    }
    const watchList = this._getWatchFile(res);
    this.watchList = watchList;
    const watchNames = new Array();
    this.defaultWatchList = []
    watchList.forEach(watch => {
      const name = (watch.name).toUpperCase()
      if (this.defaultNames.includes(name)) {
        this.defaultWatchList.push(watch);
      }
      const array = watch.path.split("/");
      watchNames.push(array[array.length - 1]);
    });
    console.log("watchNames:",JSON.stringify(watchNames));
    
    for (let index = 0; index < dials.length; index++) {
      const names = dials[index].fileName.split("/");
      const fileName = names[names.length-1];
      console.log("fileName:",fileName,watchNames.includes(fileName.toUpperCase()));
      // 是否为使用中的表盘
      dials[index].active = false
      // 判断 watchNames 是否为 WATCH0~WATCH3
      const isDefaultWatch = /^WATCH[0-3]$/i.test(fileName.toUpperCase());
      if (watchNames.includes(fileName.toUpperCase())) {
        // const added=true;
        dials[index].added = true;
        dials[index].del = false; 
        if (isDefaultWatch) {
          dials[index].del = true; 
        }
      } else {
        dials[index].added = false;
        dials[index].del = true; 
      }
    }
    // 统计有效文件名数量（排除精确匹配项和BGP开头的文件）
    const validCount = watchNames.filter(fileName => {
      const upperCaseName = fileName.toUpperCase();
      return (
        !this.systemNames.includes(upperCaseName) &&    // 排除精确匹配项
        !this.defaultNames.includes(upperCaseName) &&    // 排除精确匹配项
        !upperCaseName.startsWith("BGP")            // 排除BGP开头
      );
    }).length;

    console.log("现在有除了默认表盘数量：" , validCount);
    this.setData({ 
      list: dials ,
      dialsNum:validCount,
    });
    setTimeout(()=>{
      this.getUsingWatch();
    },2000)
  },
  // 切换表盘
  chooseWatch(value){
    // console.log(value);
    const watchNames = value.split("/");
    const watchName = watchNames[watchNames.length-1];
    const list =  this.data.list;
    for (let index = 0; index < list.length; index++) {
      const item = list[index];
      const names = item.fileName.split("/");
      const name = names[names.length-1];
      if (name.toUpperCase() === watchName.toUpperCase()) {
        list[index].added = true;
        list[index].active = true;
      }
    }
    this.setData({list});
  },
  // 清除选中表盘 
  clearActive(){
    const list = this.data.list;
    for (let index = 0; index < list.length; index++) {
      const item = list[index];
      item.active = false;
    }
    this.setData({list});
  },
  // 获取当前正在使用的表盘
  getUsingWatch(){
    RCSPOpWatchDial?.getUsingDial().then((res) => {
      //正在使用的表盘
      console.log("当前在使用的表盘",res);
      if (res.path) {
        this.chooseWatch(res.path);
      }
    }).catch((error) => {
        //失败
        console.error("当前使用表盘，失败：", error);
    })
  },
  clickReadDialFile() {
    if (this.data.isTransfering) { return };
    wx.chooseMessageFile({
      count: 1, success: (res) => {
        const tempFilePaths = res.tempFiles;
        console.log("tempFilePath:", tempFilePaths);
        this.setData({ fileStatus: 1 });
        const fs = wx.getFileSystemManager();
        fs.getFileInfo({
          filePath: tempFilePaths[0].path,
          success: (res) => {
            let fd = fs.openSync({ filePath: tempFilePaths[0].path });
            let uint8 = new Uint8Array(res.size);
            fs.read({
              fd: fd,
              arrayBuffer: uint8.buffer,
              length: res.size,
              success: (_res) => {
                this.lastModifyTime = tempFilePaths[0].time;
                this.dialData = uint8;

                const packResFormat = new JlModel.PackResFormat();
                const fileName = tempFilePaths[0].name;
                console.log("读取文件成功", uint8, "fileName:" + fileName);
                const fileInfoData = packResFormat.getFileData(uint8, fileName + '.json');
                if (fileInfoData == undefined) {
                  this.setData({ fileStatus: 0, fileName: '', fileInfo: '' });
                  wx.showToast({
                    title: "获取文件失败 ", 
                    icon: 'none', 
                    duration: 2000 
                  });
                } else {
                  const fileInfo = JlModel.Uint8ArrayToString(fileInfoData);
                  this.setData({
                    fileStatus: 2, fileName: fileName, fileInfo: fileInfo
                  });

                  this.startTransferDialFile();
                }
              }, complete: (_res) => {
                fs.close({ fd });
              }
            });
          }
        });

      }
    });
  },
  // 开始传输
  startTransferDialFile() {
    //开始传输
    const fileName = this.data.fileName.trim();
    if (fileName.length == 0) {
      wx.showToast({ title: "文件名不能为空" });
      return;
    }
    try{
      RCSPOpSystemInfo?.getSystemInfo().then((systemInfo) => {
        if (systemInfo.callStatus == 1) {
          wx.showToast({ title: '通话中，不可操作', icon: 'none' });
        } else if (systemInfo.callStatus == 0) {
          if (this.data.fileStatus == 2 && this.dialData.length > 0) {
            const _callback = {
              onError: (code) => {
                this.setData({ transferProgressText: "传输失败" + code });
                this.hideModal();
              },
              onStart: () => {
                this.setData({ modalTitle: "安装...", transferProgressText: "开始传输", isTransfering: true })
                this.showModal()
              },
              onProgress: (progress) => {
                this.setData({ transferProgressText: "正在传输，进度：" + progress, progress: progress })
    
              },
              onSuccess: () => {
                this.setData({ transferProgressText: "传输成功", isTransfering: false })
                this.hideModal()
                wx.showToast({ title: "安装完成" })
                const list = this.data.list;
                const index = this.data.index;
                list[index].added = true;
                list[index].active = true;
                this.setData({
                  list
                })
              },
              onCancel: (_code) => {
                this.setData({ transferProgressText: "传输取消", isTransfering: false })
                this.hideModal()
              }
            };
            console.log("addWatchResourseFile", fileName, this.dialData, this.lastModifyTime);
            RCSPOpWatchDial?.addWatchResourseFile(this.dialData, fileName, this.lastModifyTime, true, _callback).then((res) => {
              if (res instanceof JlModel.OPDirectoryBrowse.File) {
                RCSPOpWatchDial?.setUsingDial(res);
                console.log("安装完成后的");
              } else if (res == undefined) {
                console.error("传输完成后找不到该文件");
              } else {
                console.log("目录浏览的相对路径：path:" + res);
              }
            }).catch((error) => {
              console.error(error);
              wx.showToast({ title: "添加表盘失败，" + error });
            });
          } else {
            wx.showToast({ title: "请先读取表盘文件" });
            return;
          }
        }
      })
    }catch(e){
      this.hideModal()
      console.log(e);
      
      wx.showToast({title:"添加表盘失败"})
    }
    
  },
  _getWatchFile(fileList) {
    // const file = "WATCH"
    // const result = new Array<OPDirectoryBrowse.File>()
    // for(let index =0;index<fileList.length;index++){
    //   const element = fileList[index]
    //   if(element.getName()?.toUpperCase().includes(file)){
    //     result.push(element)
    //   }
    // }
    return fileList

  },
  // 设置表盘
  setWatch(index){
    const item=this.data.list[index]
    console.log("setWatch:",index,JSON.stringify(item))
    const names=item.fileName.split("/")
    const name=names[names.length-1]
    let i=0
    while(i<this.watchList.length){
    // for(let index=0;index<this.watchList.length;index++){
      const watch=this.watchList[i]
      const watchNames = watch.path.split("/")
      const watchName=watchNames[watchNames.length-1]
      console.log("watchName:"+watchName,"name:"+name);
      
      if(watchName.toUpperCase()===name.toUpperCase()){
        break
      }
      i++
    }
    if(i < this.watchList.length){
      this._setWatch(this.watchList[i],index)
    }
  },
  // 设置表盘
  _setWatch(file, index){
    console.log("_setUsingDial:"+JSON.stringify(file));
      RCSPOpWatchDial?.setUsingDial(file).then((_res)=>{
        console.log("设置表盘：",_res);
        const list= this.data.list
        const lastIndex= this.data.lastIndex
        if (lastIndex !== -1) {
          list[lastIndex].active = false
        }
        list[index].active=true
        this.setData({
          lastIndex: index, // 记录上一个索引
          list: list
        })
        wx.showToast({title:"设置表盘成功"})
      }).catch((error)=>{
        wx.showToast({title:"设置表盘失败，"+error})
      })
  },
  // 删除表盘
  deleteWatch(e){
    const index = e.currentTarget.dataset.index;
    
    const item=this.data.list[index]
    console.log("deleteWatch:",index,JSON.stringify(item))
    const names=item.fileName.split("/")
    const name=names[names.length-1]
    let i=0
    while(i<this.watchList.length){
    // for(let index=0;index<this.watchList.length;index++){
      const watch=this.watchList[i]
      const watchNames=watch.path.split("/")
      const watchName=watchNames[watchNames.length-1]
      console.log("watchName:"+watchName,"name:"+name);
      
      if(watchName.toUpperCase()===name.toUpperCase()){
        break
      }
      i++
    }
    if(i<this.watchList.length){
      this._dialOperateDeleteDial(this.watchList[i],index)

    }
    // wx.showModal({
    //   title:"删除表盘"
    // })
    
  },
  // 删除表盘
  _dialOperateDeleteDial(file, index){
    console.log("_dialOperateDeleteDial:"+file);
    wx.showModal({
      title:"删除表盘",
      content:"确定要删除表盘文件?",
      confirmText:"删除",
      cancelText:"取消",
      success:(res)=>{
        if(res.confirm){
          RCSPOpWatchDial?.deleteDial(file).then((_res)=>{
            wx.showToast({title:"删除表盘成功"})
           const list= this.data.list
           list[index].added=false
           list[index].del=true
           console.log("删除成功，开始设置默认：" + JSON.stringify(this.defaultWatchList[0]));
           RCSPOpWatchDial?.setUsingDial(this.defaultWatchList[0]).then((_res)=>{
             console.log("设置表盘：",_res);
             wx.showToast({title:"设置表盘成功，"+_res})

           }).catch((error)=>{
             wx.showToast({title:"设置表盘失败，"+error})
           })
           this.setData({list})
          RCSPOpWatchDial?.getWatchResourseFileList().then((res) => {
            console.log("获取表盘列表", res);
            this.reFresh(res)
          })
          }).catch((error)=>{
            wx.showToast({title:"删除表盘失败，"+error})
          })
        }
        // else if(res.cancel){}
      }

    })
  },
  showModal: function () {
    this.setData({
      showModal: true
    });
  },
  // 重置进度条
  hideModal: function () {
    this.setData({
      showModal: false,
      progress: 0  // 重置进度条
    });
  },
  // 点击事件
  onItemClick(e) {
    // console.log("获取当前使用的表盘");
    const index = e.currentTarget.dataset.index
    console.log("onItemClick index====" + index)
  },
  // 下载
  onInstall(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      index
    })
    console.log("onInstall index====" + index, RCSPOpWatchDial);
    if (!this.data.list[index].added) {
      console.log("现在有表盘数量：" + this.data.dialsNum);
      if (this.data.dialsNum >= 2) {
        wx.showToast({
          title: '表盘仅能安装两个，请手动移除多余表盘',
          icon: 'fail',
        });
        return
      }
      this.download(this.data.list[index])
    } else{
      if (!this.data.list[index].active) {
        this.setWatch(index)
      }
    }
  },
  // 下载
  download(item) {
    // this.setData({modalTitle:"开始下载"})
    this.showModal()
    const that = this
    const url = item.fileName
    const downloadTask = wx.downloadFile({
      url: url,
      success: function (res) {
        if (res.statusCode === 200) {
          console.log('下载成功', res.tempFilePath);
          const localPath = res.tempFilePath
          that.setData({ fileStatus: 1 })
          const fs = wx.getFileSystemManager()
          fs.getFileInfo({
            filePath: localPath,
            success: (res) => {
              let fd = fs.openSync({ filePath: localPath })
              let uint8 = new Uint8Array(res.size)
              fs.read({
                fd: fd,
                arrayBuffer: uint8.buffer,
                length: res.size,
                success: (_res) => {
                  that.lastModifyTime = 0//tempFilePaths[0].time
                  that.dialData = uint8

                  const packResFormat = new JlModel.PackResFormat()
                  const names = item.fileName.split('/')
                  const fileName = names[names.length - 1]
                  const fileInfoData = packResFormat.getFileData(uint8, fileName + '.json')
                  console.log("读取文件成功", uint8, "item.fileName:" + JSON.stringify(item), JSON.stringify(fileInfoData));
                  if (fileInfoData == undefined) {
                    that.setData({ fileStatus: 0, fileName: '', fileInfo: '' })
                    wx.showToast({
                      title: "获取文件失败 ", 
                      icon: 'none', 
                      duration: 2000 
                    });
                    that.hideModal()
                  } else {
                    const fileInfo = JlModel.Uint8ArrayToString(fileInfoData)
                    that.setData({
                      fileStatus: 2, fileName: fileName, fileInfo: fileInfo
                    })
                    that.startTransferDialFile()
                  }
                }, complete: (_res) => {
                  fs.close({ fd })

                }
              })
            }
          })
        }
      },
      fail: function (err) {
        console.log('下载失败', err);
        that.hideModal()
      }
    });
    downloadTask.onProgressUpdate((res) => {
      console.log("onProgressUpdate", res.progress);
      const progress = res.progress
      this.setData({
        modalTitle: '下载...',
        progress: progress
      })

    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    wx.setKeepScreenOn({
      keepScreenOn: true,
      success() {
        console.log('屏幕保持常亮设置成功');
      },
      fail(err) {
        console.error('屏幕保持常亮设置失败', err);
      }
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // 当离开页面时，可以关闭屏幕常亮
    wx.setKeepScreenOn({
      keepScreenOn: false,
      success() {
        console.log('屏幕常亮设置已关闭');
      }
    });
    // 注销回调
    RCSPOpWatchDial?.unregisterEventCallback(callback)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})